package com.itravel.cms.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.itravel.cms.services.ExcelDataService;
import com.itravel.cms.utils.AppConfig;

@Controller
@RequestMapping("/dataManage")
public class DataManageController extends AbstractController {
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private ExcelDataService excelDataService;
	
	@Autowired
	private AppConfig appConfig;
	
	public AppConfig getAppConfig() {
   	return appConfig;
   }

	public void setAppConfig(AppConfig appConfig) {
   	this.appConfig = appConfig;
   }

	@RequestMapping("index")
	public String index(Model model){
		return "index";
	}
	
	@RequestMapping("/doImport")
	public void doImport(@RequestParam("file")MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response)  {
   	String uploadedExcelPath = appConfig.getUploadedExcelPath();
   	String filePath = uploadedExcelPath + File.separator + new Date().getTime()+".xls";
   	logger.info("Upload excel path is " + uploadedExcelPath);
      try {
			saveFile(multipartFile, filePath);
			excelDataService.importDataWithFilePath(filePath);
			File file = new File(filePath);
			if (file != null && file.exists()) {
				file.delete();
			}
			response.setContentType("text/html");
      	response.getWriter().println("TRUE");
			
//			JSONObject jsonObject = new JSONObject();
//         jsonObject.put("path", uploadedExcelPath);
//
//         response.setContentType("text/html");
//         response.getWriter().println(jsonObject.toString());
      	
      } catch (IOException e) {
			File file = new File(filePath);
			if (file != null && file.exists()) {
				file.delete();
			}
         e.printStackTrace();
      	try {
	         response.getWriter().println("FALSE");
         } catch (IOException e1) {
	         e1.printStackTrace();
         }
 		}
	}
	
}